from django.utils.deprecation import MiddlewareMixin  # 导入Django的中间件基类
from django.http import JsonResponse  # 导入Django的JsonResponse类，用于返回JSON响应
from tools.myjwt import mjwt  # 导入自定义的JWT工具
from tools.myredis import r  # 导入自定义的Redis工具
import time, json  # 导入时间模块和json模块
from django_redis import get_redis_connection
import json
import time

class PermissionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 定义白名单
        white_list = ['/myadmin/login/', '/login/']
        # 获取接口地址，用于从redis中判断
        url = request.path
        print(url)
        if url not in white_list:
            # 解析认证
            try:
                token = request.headers.get('Authorization')
                data = mjwt.jwt_decode(token)
                redis = get_redis_connection("admin")
                # 判断token是否过期
                if int(time.time()) > int(data['data']['exp']):
                    return JsonResponse({"message": "登录已过期", "code": 401})

                # 判断用户是否已登出
                # 用户所使用的token和其在redis中存token的相同，则说明用户已等登出，该token是恶意攻击
                if redis.get(f"dingxiang_admin_{data['data']['id']}") is not None:
                    if redis.get(f"dingxiang_admin_{data['data']['id']}").decode() == token:
                        return JsonResponse({"message": "用户已登出", "code": 405})

                # 判断用户能否访问接口
                interfaces = json.loads(redis.get(f"dingxiang_role_{data['data']['role']}"))
                print(interfaces)
                if url not in interfaces.get("interface_list"):
                    return JsonResponse({"message": "该用户角色无权访问该接口", "code": 403})
            except Exception as e:
                print(e)
                return JsonResponse({"code": 401})
